package com.tool;

import com.service.Accountservice;
import com.service.AccountserviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@Component
public class proxyfatory {
    private Object tager;
    @Autowired
    private TranseactionManger transeactionManger;
    public proxyfatory(Accountservice tager) {
        this.tager = tager;
    }

    public void setTager(Accountservice tager) {
        this.tager = tager;
    }

    public proxyfatory() {
    }

    public Object getTager(){
        return  Proxy.newProxyInstance(tager.getClass().getClassLoader(),
                tager.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object value=null;
                        if (tager.getClass().getName().equals(AccountserviceImpl.class.getName()))
                        {
                            try {
                                transeactionManger.begin();
                                value=method.invoke(tager,args);
                                transeactionManger.commit();
                                return value;
                            }catch (Exception e){
                                transeactionManger.rollback();
                                throw new RuntimeException("寻找错误");
                            }finally {
                                transeactionManger.release();
                            }
                        }
                        return value;
                    }
                });
    }
}
